import React, { Component } from 'react'
import './css/upload.css';

class UploadTem extends Component {
    constructor() {
        super();
        this.state = {
            img: null,
            upRes: ''
        }
    }
    handlerChange() {
        const that = this
        const file = document.getElementById('file').files[0]
        if (file.type !== 'image/jpeg') {
            alert('请上传jpg图片')
            return
        }
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (result) {
            that.setState({
                img: this.result,
                upRes: '',
            })
        }
    }

    update = () => {
        const that = this
        const file = document.getElementById('file').files[0]
        var style = document.getElementById('temSty').value;
        var pay = document.getElementById('temPay').value

        const formData = new FormData();
        formData.append('file', file);
        fetch(`https:www.h5fd.xyz:2021/test/addImg2/?style=${style}&pay=${pay}`, {
            method: 'POST',
            body: formData,
        })
            .then(res => res.text())
            .then(res => {
                if (res == 'success') {
                    alert('上传成功');
                    that.setState({
                        img: null,
                        upRes: 'success',
                        val1: '',
                        val2: ''
                    })
                }
            })
    }
    render() {
        return (
            <div className="add">
                <h2 className='h2'>添加模板</h2>
                <input className="file" type="file" id="file" accept="image/*" onChange={this.handlerChange.bind(this)} />
                {
                    this.state.img ?
                        <div className="upMessage">
                            <img className="upImg" src={this.state.img} alt="" />
                            <div className='inputBox'>
                                <input className="upStyle" placeholder="输入模板风格" id="temSty" />
                                <input className="upPay" placeholder="输入模板价格" id="temPay" />
                                <button className="upBtn" onClick={this.update.bind(this)}>上传</button>
                            </div>
                        </div>
                        : <div className='upMessage'>
                            <img className="upImg" src={this.state.img} alt="" />
                            <div className='inputBox'>
                                <input className="upStyle" placeholder="输入模板风格" id="temSty" />
                                <input className="upPay" placeholder="输入模板价格" id="temPay" />
                                <button className="upBtn" onClick={this.update.bind(this)}>上传</button>
                            </div>
                        </div>
                }
            </div>
        )
    }
}

export default UploadTem;